﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using KPIReport.Library;
using KPIReport.Library.DomainObject.Administration.Catalog;
using KPIReport.Library.Enum;
using KPIReport.Library.Interfaces;

namespace KPIReport.Library.DataAccess.Administration.Catalog
{
    public partial class ProdukKonversiSatuanRepo
    {
        public bool SaveUpload(List<ProdukKonversiSatuan> domains)
        {
            bool result = false;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlTransaction txn = conn.BeginTransaction();
                try
                {

                    SqlCommand cmdGetID = conn.CreateCommand();
                    cmdGetID.CommandText = "SELECT ISNULL(MAX(ID),0) FROM ProdukKonversiSatuan_temp";
                    cmdGetID.CommandType = CommandType.Text;
                    cmdGetID.Transaction = txn;
                    object objID = cmdGetID.ExecuteScalar();
                    int IdTemp = Convert.ToInt32(objID);
                    cmdGetID.Dispose();

                    domains.ForEach(delegate(ProdukKonversiSatuan domain)
                    {
                        IdTemp++;
                        SqlCommand cmd = conn.CreateCommand();
                        cmd.CommandText = "INSERT INTO dbo.ProdukKonversiSatuan_temp(ID,KodeProduk, NamaProduk, Status, BaseProduk, Case_Pallet, DSP_Case, EA_Case) VALUES(@ID,@KodeProduk, @NamaProduk, @Status, @BaseProduk, @CasePallet, @DSPCase, @EACase)";
                        cmd.CommandType = CommandType.Text;

                        //cmd.CommandText = "INSERT INTO dbo.ProdukKonversiSatuan(KodeProduk, NamaProduk, Status, BaseProduk, Case_Pallet, DSP_Case, EA_Case) VALUES(@KodeProduk, @NamaProduk, @Status, @BaseProduk, @CasePallet, @DSPCase, @EACase)";
                        //cmd.CommandText = "SP_ProdukKonversiSatuan_Insert";
                        //cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@ID", SqlDbType.Int).Value = IdTemp;
                        cmd.Parameters.Add("@KodeProduk", SqlDbType.NVarChar).Value = (object)domain.KodeProduk ?? DBNull.Value;
                        cmd.Parameters.Add("@NamaProduk", SqlDbType.NVarChar).Value = (object)domain.NamaProduk ?? DBNull.Value;
                        cmd.Parameters.Add("@Status", SqlDbType.NVarChar).Value = (object)domain.Status ?? DBNull.Value;
                        cmd.Parameters.Add("@BaseProduk", SqlDbType.NVarChar).Value = (object)domain.BaseProduk ?? DBNull.Value;
                        cmd.Parameters.Add("@CasePallet", SqlDbType.Int).Value = (object)domain.CasePallet ?? DBNull.Value;
                        cmd.Parameters.Add("@DSPCase", SqlDbType.Int).Value = (object)domain.DSPCase ?? DBNull.Value;
                        cmd.Parameters.Add("@EACase", SqlDbType.Int).Value = (object)domain.EACase ?? DBNull.Value;

                        cmd.Transaction = txn;
                        cmd.ExecuteNonQuery();
                        cmd.Dispose();
                    });

                    SqlCommand cmdDua = conn.CreateCommand();
                    cmdDua.CommandText = "delete from ProdukKonversiSatuan_temp where Kodeproduk is null or Kodeproduk =''";
                    cmdDua.CommandType = CommandType.Text;

                    cmdDua.Transaction = txn;
                    cmdDua.ExecuteNonQuery();
                    cmdDua.Dispose();

                    cmdDua = conn.CreateCommand();
                    cmdDua.CommandText = "delete ProdukKonversiSatuan where Kodeproduk in(select Kodeproduk from ProdukKonversiSatuan_temp)";
                    cmdDua.CommandType = CommandType.Text;

                    cmdDua.Transaction = txn;
                    cmdDua.ExecuteNonQuery();
                    cmdDua.Dispose();

                    cmdDua = conn.CreateCommand();
                    cmdDua.CommandText = @"INSERT INTO ProdukKonversiSatuan(
                                           [KodeProduk]
                                          ,[NamaProduk]
                                          ,[Status]
                                          ,[BaseProduk]
                                          ,[Case_Pallet]
                                          ,[DSP_Case]
                                          ,[EA_Case]
                                          )
                                        SELECT 
                                          [KodeProduk]
                                         ,[NamaProduk]
                                         ,[Status]
                                         ,[BaseProduk]
                                         ,[Case_Pallet]
                                         ,[DSP_Case]
                                         ,[EA_Case]
                                          
                                        FROM ProdukKonversiSatuan_temp ";

                    cmdDua.CommandType = CommandType.Text;

                    cmdDua.Transaction = txn;
                    cmdDua.ExecuteNonQuery();
                    cmdDua.Dispose();

                    result = true;
                    txn.Commit();
                }
                catch (Exception ex)
                {
                    txn.Rollback();
                    throw (ex);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open) conn.Close();
                }


            }
            return result;
        }

        public List<ProdukKonversiSatuan> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<ProdukKonversiSatuan> tt = new List<ProdukKonversiSatuan>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);


                    //cmd.CommandText = "SP_transaksihdr_GridPage";
                    ////cmd.Parameters.Add("@startRow", SqlDbType.Int).Value = startRow;
                    ////cmd.Parameters.Add("@endRow", SqlDbType.Int).Value = endRow;
                    ////cmd.Parameters.Add("@sortName", SqlDbType.VarChar).Value = sortName;
                    ////cmd.Parameters.Add("@sortOrder", SqlDbType.VarChar).Value = sortOrder;
                    ////cmd.Parameters.Add("@param", SqlDbType.VarChar).Value = parameters;

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      KodeProduk,NamaProduk");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      dbo.ProdukKonversiSatuan ");
                    sbQuery.AppendFormat(" WHERE KodeProduk IS NOT NULL AND NamaProduk IS NOT NULL AND EA_Case <> 0 {0}", parameters);
                    sbQuery.AppendFormat(" GROUP BY KodeProduk,NamaProduk");
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    //cmd.CommandType = CommandType.StoredProcedure;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                ProdukKonversiSatuan t = new ProdukKonversiSatuan();
                                t.KodeProduk = dr[ProdukKonversiSatuan.Fields.KodeProduk] == DBNull.Value ? string.Empty : dr[ProdukKonversiSatuan.Fields.KodeProduk].ToString();
                                t.NamaProduk = dr[ProdukKonversiSatuan.Fields.NamaProduk] == DBNull.Value ? string.Empty : dr[ProdukKonversiSatuan.Fields.NamaProduk].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public object SelectScalar(SQL.Function.Aggregate function, string column, string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {

                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0})  FROM dbo.ProdukKonversiSatuan WHERE KodeProduk IS NOT NULL AND NamaProduk IS NOT NULL AND EA_Case <> 0 {1}", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }
    }
}
